import axios from "../../../../utils/axios";
const app = getApp();
Page({
  data: {
    goodsData: '',
    userSize: '',
    userInfo: '',
    address: null,
    freightPrice: 0, // 运费
    totalNum: 1, // 总数
    totalPrice: 99999, // 总价默认99999防止价格bug
    isSettingBtn: false
  },
  onLoad: function (options) {
    const eventChannel = this.getOpenerEventChannel();
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('sendDetailData', (res) => {
      let data = res.data;
      this.setData({
        goodsData: data.goodsData,
        userSize: data.userSize,
        userInfo: app.globalData.userInfo,
        totalPrice: data.goodsData.price
      })
    });
  },
  // 获取用户收货地址按钮
  getAddRess() {
    wx.chooseAddress({
      success: (res) => {
        let addressObj = {
          provinceName: res.provinceName, // 省份
          cityName: res.cityName, // 城市
          countyName: res.countyName, // 区
          detailInfo: res.detailInfo, // 详细住址
          postalCode: res.postalCode, // 邮编
          telNumber: res.telNumber, // 电话
          userName: res.userName // 收件人
        }
        this.setData({
          address: addressObj
        })
      },
      fail: err => {
        wx.getSetting({
          success: (result) => {
            console.log(result.authSetting);
            if (result.authSetting['scope.address'] == false) {
              wx.showToast({
                title: '请先授权',
                icon: 'none',
                duration: 1500,
              });
              this.setData({
                isSettingBtn: true
              })
            }
          },
          fail: () => {},
          complete: () => {}
        });
      }
    });
  },
  goToSetting() {
    wx.openSetting({
      success: (result) => {
        console.log(result.authSetting);
        if (result.authSetting['scope.address'] == true) {
          this.setData({
            isSettingBtn: false
          })
        }
      },
      fail: err => console.log(err)
    });
  },
  // 支付
  async goToPay() {
    wx.showLoading({
      title: '正在调起微信支付，请稍等...',
      mask: true,
      duration: 1500,
    });
    if (wx.getStorageSync('token') == undefined)
      return false


    // 获取参数
    let address = this.data.address;
    //  生成订单
    let res = await axios({
      url: '/api/wx/pay/createOrder',
      method: 'post',
      // data数据太难看了，等会用解构赋值
      data: {
        openid: this.data.userInfo.openId,
        appid: 'wxe4f65fd9f5a232f9',
        body: `${this.data.goodsData.storeName}订单`,
        // price: this.data.goodsData.price,
        price: this.data.totalPrice,
        orderType: "2",
        tradeType: 'JSAPI',
        detail: JSON.stringify({
          orderInfo: {
            uid: this.data.userInfo.id, // 用户id
            cartId: '', // 购物车id
            isChannel: 1, // 0公众号支付 1小程序支付
            userPhone: address.telNumber, // 手机号
            realName: address.userName, // 收件人
            status: 0,
            payType: 'weixin',
            verifyCode: '',
            mark: '',
            userAddress: `${address.provinceName} ${address.cityName} ${address.countyName} ${address.detailInfo} ${address.postalCode}`, // 收货地址
            totalNum: this.data.totalNum, // 总数
            freightPrice: this.data.freightPrice, // 运费
            totalPrice: this.data.totalPrice, // 总价
            payPrice: this.data.totalPrice, // 实际支付价格
          },
          goodDetails: [{
            productId: this.data.goodsData.id, // 商品编号
            prodAttrVid: this.data.userSize.id, // 用户尺码
          }],
        })
      },
      header: {
        'Authorization': wx.getStorageSync('token')
      }
    });
    // console.log('支付回调', res);

    // return;
    let payData = res.data;
    wx.requestPayment({
      timeStamp: payData.timeStamp,
      nonceStr: payData.nonceStr,
      package: payData.packageValue, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
      signType: 'MD5',
      paySign: payData.paySign, //签名
      // 成功
      success: paidRes => {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500,
          mask: false,
        });
        wx.reLaunch({
          url: `/components/page/payResult/payResult?msg=${paidRes.errMsg}&isPaid=${true}`,
        });
      },
      // 失败
      fail: err => {
        wx.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 1500,
          mask: false,
        });
        wx.reLaunch({
          url: `/components/page/payResult/payResult?msg=${err.errMsg}&isPaid=${false}`,
        })
      },
      complete: (res) => {}
    })
    wx.hideLoading();
  },
  // 更新价格
  priceUpDate() {
    this.setData({
      totalPrice: this.data.totalNum * this.data.goodsData.price + this.data.freightPrice
    })
  },
  // 更新数量
  numberChange(e) {
    this.setData({
      totalNum: e.detail
    });
    this.priceUpDate();
  }
})